package gautobgchanger;

import java.io.File;
import java.net.URLConnection;
import java.util.Random;
import javax.activation.MimetypesFileTypeMap;

/**
 * Program for Gnome(and only Gnome) to change your background image from a folder.
 * @author b1o
 */
public class Main {

    public static ConfReader cr;

    public static void main(String args[]) throws Exception {
        //Creates a system tray icon
        SystemTrayIcon sti = new SystemTrayIcon();
        sti.createSystemTray();
        cr = new ConfReader();
        //Checks if there is no config file
        if (!cr.configFileExcists()) {
            //Tells the system tray that it needs to open a folder selector
            //so that it can prompt the user for a folder
            sti.ShowFileChooser(false);
        }
        while (true) {
            String file = getBg(cr);
            //runs a gnome command that changes the background image in gnome till the value of file
            Runtime.getRuntime().exec("gconftool-2 -s -t string /desktop/gnome/background/picture_filename " + file);
            //tell this thread to sleep for the interval that was set in the config file
            Thread.currentThread().sleep(cr.getInterval() * 1000);
        }
    }
//files[new Random().nextInt(files.length)].getAbsolutePath()

    /**
     * Checks to see if the file is an image, if it isn't it will get the file again at random until it is an image
     * @param cr ConfReader to read the config file
     * @return String - Path to image
     * @throws Exception
     */
    private static String getBg(ConfReader cr) throws Exception {
        //lists the files in the Wallpaper folder
        File[] files = new File(cr.getPath()).listFiles();
        //gets a random file to use as a background
        File file = files[new Random().nextInt(files.length)];
        //Gets the mime type of the file, if it is an image it would look like this: image/jpeg
        String contentType = URLConnection.getFileNameMap().getContentTypeFor(file.getPath());
        //checks if content type is null or if its mime type doesn't contain image,
        //it loops until contentType contains image
        while (contentType == null || !contentType.contains("image")) {
            //Randoms itself to a new file
            file = files[new Random().nextInt(files.length)];
            //gets the content type again
            contentType = URLConnection.getFileNameMap().getContentTypeFor(file.getPath());
        }
        //returns an image file
        return file.getAbsolutePath();
    }

    public static ConfReader getConfReader() {
        return cr;
    }
}
